package com.student.web;


import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.common.model.BaseUser;
import com.common.model.Project;
import com.common.model.StudentUser;
import com.common.model.TeacherUser;
import com.common.model.TimePlan;
import com.common.util.Md5Encrypt;
import com.student.model.IntentProject;
import com.student.service.StudentService;
import com.student.util.UploadFile;
import com.teacher.model.ProjAndProf;
import com.teacher.util.Upload;

@Controller
@RequestMapping("/student")
public class StudentController {
	
	private final String SUCCESS = "success";
	private final String FAIL = "fail";

	@Autowired
	private StudentService ss;

	/**
	 * 登陆处理及跳转到个人信息显示页面
	 * @return
	 */
	@RequestMapping("/info")
	public ModelAndView toStudentInfo(HttpServletRequest request,HttpSession session) {
		ModelAndView mav = new ModelAndView();
		
		//获取学生信息
		Integer id = ((StudentUser)request.getSession().getAttribute("user")).getId();
		StudentUser student = ss.studentInfo(id);
		student.setUserType("student");
		session.setAttribute("user", student);
		//获取意向题目
		ArrayList<IntentProject> intents = ss.getIntentProjects(id);
		session.setAttribute("intents", intents);
		mav.addObject("intents", intents);
		mav.addObject("title", "学生个人信息");
		mav.setViewName("student/info");
		return mav;
	}
	
	/**
	 * 跳转到修改基本信息页面
	 * @return
	 */
	@RequestMapping("/updateInfo")
	public ModelAndView toUpdateStudentInfo(HttpServletRequest request,HttpSession session) {
		ModelAndView mav = new ModelAndView();
		ArrayList<IntentProject> intents = (ArrayList<IntentProject>)request.getSession().getAttribute("intents");
		mav.addObject("intents", intents);
		session.setAttribute("intents", intents);
		mav.addObject("title", "修改个人基本信息");
		mav.setViewName("student/updateInfo");
		return mav;
	}
	
	/**
	 * 修改个人信息
	 * @param telephone
	 * @param qq
	 * @param request
	 * @return
	 */
	@RequestMapping("/a_updateInfo")
	@ResponseBody
	public String UpdateStudentInfo(
			@RequestParam("telephone") String telephone,@RequestParam("qq") String qq,
			HttpServletRequest request) {
		Integer id = ((StudentUser) request.getSession()
				.getAttribute("user")).getId();
		boolean result = ss.updateInfo(id, telephone, qq);
		if(result){
			StudentUser student = (StudentUser)request.getSession().getAttribute("user");
			student.setTelephone(telephone);
			student.setQq(qq);
			student.setUserType("student");
			request.getSession().setAttribute("user", student);
		}
		return result ? SUCCESS : FAIL;
	}
	
	/**
	 * 跳转到修改密码页面
	 * @return
	 */
	@RequestMapping("/updatePassword")
	public ModelAndView toUpdateStudentPassword() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("title", "修改个人密码");
		mav.setViewName("student/updatePassword");
		return mav;
	}
	
	/**
	 * 验证用户输入的旧密码是否正确
	 * 
	 * @param password
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/validatePassword")
	public String validatePassword(@RequestParam("password")String password, HttpServletRequest request) {
		String pwd = ((StudentUser) request.getSession().getAttribute(
				"user")).getPassword();
		String input = Md5Encrypt.encrypt(password);
		return input.equals(pwd) ? SUCCESS : FAIL;
	}
	/**
	 * 修改密码
	 * @param oldPass
	 * @param newPass
	 * @param request
	 * @return
	 */
	@RequestMapping("/a_updatePassword")
	@ResponseBody
	public String UpdateStudentPassword(@RequestParam("password") String password,
			HttpServletRequest request) {
		Integer id = ((StudentUser) request.getSession()
				.getAttribute("user")).getId();
		boolean result = ss.updatePassword(id, Md5Encrypt.encrypt(password));
		return result ? SUCCESS : FAIL;
	}
	
	/**
	 * 跳转到题目列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/projects{page}")
	public ModelAndView toShowProjects(@PathVariable("page")int page,
			HttpServletRequest request,HttpSession session){
		ModelAndView mav = new ModelAndView();
		//时间判断
		boolean available;
		Integer collegeId = ((StudentUser)request.getSession().getAttribute("user")).getClassInfo().getBranch().getProf().getDepartment().getCollege().getId();
		Integer depart_id = ((StudentUser)request.getSession().getAttribute("user")).getClassInfo().getBranch().getProf().getDepartment().getId();
		TimePlan timeplan = ss.getTimePlan(collegeId);
		Timestamp time = new Timestamp(new Date().getTime());
		int start = time.compareTo(timeplan.getStudentChooseTimeStart());
		int end = time.compareTo(timeplan.getStudentChooseTimeEnd());
		if((start>=0)&&(end<=0)) {
			available = true;
			ArrayList<TeacherUser> teachers = ss.getTeachers(depart_id);
			Integer prof_id = ((StudentUser)request.getSession().getAttribute("user")).getClassInfo().getBranch().getId();
			ArrayList<Project> projects = ss.getProjects(prof_id,page);
			ArrayList<Project> intents = (ArrayList<Project>)request.getSession().getAttribute("intents");
			mav.addObject("teachers",teachers);
			mav.addObject("projects", projects);
			mav.addObject("intents", intents);
			mav.addObject("page",page);
		}
		else available = false;
		mav.setViewName("student/projects");
		mav.addObject("title", "题目列表");
		mav.addObject("available",available);
		return mav;
	}
	
	/**
	 * 跳转到某位老师全部题目的显示页面
	 * @param tea_id
	 * @param request
	 * @return
	 */
	@RequestMapping("/getProjectsByTeacher{tea_id}&{page}")
	public ModelAndView toShowProjectsByTeacher(@PathVariable("tea_id")int tea_id,@PathVariable("page")int page,
			HttpServletRequest request,HttpSession session) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("student/projectsByTeacher");
		Integer depart_id = ((StudentUser)request.getSession().getAttribute("user")).getClassInfo().getBranch().getProf().getDepartment().getId();
		ArrayList<TeacherUser> teachers = ss.getTeachers(depart_id);
		ArrayList<Project> projects = ss.getProjectsByTeacher(tea_id,page);
		ArrayList<Project> intents = (ArrayList<Project>)request.getSession().getAttribute("intents");
		mav.addObject("tea_id",tea_id);
		mav.addObject("intents", intents);
		mav.addObject("teachers",teachers);
		mav.addObject("projects", projects);
		mav.addObject("page",page);
		mav.addObject("title", "dd题目列表");
		return mav;
	}
	
	
	/**
	 * 跳转到意向题目显示页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/intentProjects")
	public ModelAndView toShowIntentProjects(HttpServletRequest request,HttpSession session) {
		ModelAndView mav = new ModelAndView();
		boolean available;
		Integer collegeId = ((StudentUser)request.getSession().getAttribute("user")).getClassInfo().getBranch().getProf().getDepartment().getCollege().getId();
		TimePlan timeplan = ss.getTimePlan(collegeId);
		Timestamp time = new Timestamp(new Date().getTime());
		int start = time.compareTo(timeplan.getStudentChooseTimeStart());
		int end = time.compareTo(timeplan.getStudentChooseTimeEnd());
		if((start>=0)&&(end<=0)) {
			available = true;
		}
		else available = false;
		ArrayList<IntentProject> intents = (ArrayList<IntentProject>)request.getSession().getAttribute("intents");
		mav.addObject("intents", intents);
		mav.setViewName("student/intentProjects");
		mav.addObject("title", "意向题目列表");
		mav.addObject("available", available);
		return mav;
	}
	/**
	 * 增加意向题目
	 * @param pro_id
	 * @param message
	 * @param request
	 * @return
	 */
	@RequestMapping("/a_addIntent")
	@ResponseBody
	public String addIntentProject(@RequestParam("pro_id")Integer pro_id,@RequestParam("message")String message,
			HttpServletRequest request,HttpSession session) {
		ArrayList<IntentProject> intents = (ArrayList<IntentProject>)request.getSession().getAttribute("intents");
		Integer stu_id = ((StudentUser)request.getSession().getAttribute("user")).getId();
		String telephone = ((StudentUser)request.getSession().getAttribute("user")).getTelephone();
		String qq = ((StudentUser)request.getSession().getAttribute("user")).getQq();
		if(telephone.equals("")&&qq.equals("")) {
			return "null";
		}
		 //如果意向题目已存在，返回exist
		IntentProject project = new IntentProject();
		int i = 0;
        while(i<intents.size()) {
        	project = intents.get(i);
        	if(project.getProject().getId().equals( pro_id)) {
        		return "exist";
        	}
        	i++;
        }
        if(intents.size()==5) {
			return "full";
		}
		//添加意向
        int level = intents.size() + 1;
		boolean result = ss.addIntentProject(level, pro_id, stu_id, message);
		ArrayList<IntentProject> intent = ss.getIntentProjects(stu_id);
		session.setAttribute("intents", intent);
		return result ? SUCCESS : FAIL;
	}
	/**
	 * 调整意向优先级
	 * @param id
	 * @param level
	 * @param request
	 * @return
	 */
	@RequestMapping("/a_updateIntent")
	@ResponseBody
	public String updateIntent(@RequestParam("id")Integer id,@RequestParam("option")String option,
			@RequestParam("level")int level,HttpServletRequest request,HttpSession session) {
		ArrayList<IntentProject> intents = (ArrayList<IntentProject>)request.getSession().getAttribute("intents");
		if((level==1&&option.equals("up"))||(level==intents.size()&&option.equals("down")))
			{return "null";}
		IntentProject pro1 = new IntentProject();
		IntentProject pro2 = new IntentProject();
		for(int i= 0;i<intents.size();i++)
		{
			boolean r1 = false;
			boolean r2 = false;
			pro1 = intents.get(i);
			if(pro1.getId().equals(id)) {
				if(option.equals("up")) {
					pro2 = intents.get(i-1);
					r1 = ss.updateIntent(id, pro2.getLevel());
					r2 = ss.updateIntent(pro2.getId(), level);
				}
				if(option.equals("down")) {
					pro2 = intents.get(i+1);
					r1 = ss.updateIntent(id, pro2.getLevel());
					r2 = ss.updateIntent(pro2.getId(), level);
				}
				if(r1&&r2) {
					Integer stu_id = ((StudentUser)request.getSession().getAttribute("user")).getId();
					ArrayList<IntentProject> intent = ss.getIntentProjects(stu_id);
					session.setAttribute("intents", intent);
					return "success";
				}
			}
		}
		return "fail";
	}
	
	/**
	 * 移除意向题目
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/a_removeIntent")
	@ResponseBody
	public String removeIntent(@RequestParam("id")Integer id,
			HttpServletRequest request,HttpSession session) {
		boolean result = ss.removeIntent(id);
		if(result) {
			Integer stu_id = ((StudentUser)request.getSession().getAttribute("user")).getId();
			ArrayList<IntentProject> intents = ss.getIntentProjects(stu_id);
			for(int i=0;i<intents.size();i++)
			{
				IntentProject temp = intents.get(i);
				ss.updateIntent(temp.getId(), i+1);
			}
			intents = ss.getIntentProjects(stu_id);
			session.setAttribute("intents", intents);
		}
		return result ? SUCCESS : FAIL;
	}
	
	/**
	 * 更新留言
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/a_updateMessage")
	@ResponseBody
	public String updateIntentMessage(@RequestParam("id")Integer id,@RequestParam("message")String message,
			HttpServletRequest request,HttpSession session) {
		boolean result = ss.updateMessage(id, message);
		Integer stu_id = ((StudentUser)request.getSession().getAttribute("user")).getId();
		ArrayList<IntentProject> intents = ss.getIntentProjects(stu_id);
		session.setAttribute("intents", intents);
		return result ? SUCCESS : FAIL;
	}
	
	/**
	 * 转到最终选题显示页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/finalProject")
	public ModelAndView toShowFinalProject(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("student/finalProject");
		int stu_id = ((StudentUser)request.getSession().getAttribute("user")).getId();
		Project project = ss.getFinalProject(stu_id);
		mav.addObject("project", project);
		mav.addObject("title", "题目列表");
		return mav;
	}
	
	/**
	 * 转到论文提交页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/submit")
	public ModelAndView toShowSubmit(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		//时间判断
		String available = "none";
		Integer collegeId = ((StudentUser)request.getSession().getAttribute("user")).getClassInfo().getBranch().getProf().getDepartment().getCollege().getId();
		TimePlan timeplan = ss.getTimePlan(collegeId);
		Timestamp time = new Timestamp(new Date().getTime());
		int start1 = time.compareTo(timeplan.getMiddleCheckTimeStart());
		int end1 = time.compareTo(timeplan.getMiddleCheckTimeEnd());
		if((start1>=0)&&(end1<=0)) {
			available = "middle";
		}
		int start2 = time.compareTo(timeplan.getFinalCheckTimeStart());
		int end2 = time.compareTo(timeplan.getFinalCheckTimeEnd());
		if((start2>=0)&&(end2<=0)) {
			available = "final";
		}
		int stu_id = ((StudentUser)request.getSession().getAttribute("user")).getId();
		Project project = ss.getFinalProject(stu_id);
		mav.addObject("available", available);
		mav.addObject("project", project);
		mav.setViewName("student/submit");
		mav.addObject("title", "题目列表");
		return mav;
	}
	
	/**
	 * 提交论文
	 * @param essay
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updatePath{essay}")
	@ResponseBody
	public String updateCommitmentsPath(MultipartFile file,@PathVariable("essay")String essay,
			HttpServletRequest request) throws Exception {
		boolean result = false;
		String stu_no = ((StudentUser)request.getSession().getAttribute("user")).getNo();
		String diskDirPath  = request.getSession().getServletContext().getRealPath("/")+"upload/student/";
		String path = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath() + "/upload/student/";
		int index=file.getOriginalFilename().lastIndexOf(".");
		String fileExt="";
		if(index>-1){
			fileExt=file.getOriginalFilename().substring(index);
		}
		System.out.println(fileExt);
		path=path+stu_no+fileExt;
		//filepath+=fileExt;
		File dir=new File(diskDirPath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		file.transferTo(new File(diskDirPath+stu_no+fileExt));
		
		int stu_id = ((StudentUser)request.getSession().getAttribute("user")).getId();
		if(essay.equals("temp"))
			result = ss.updateCommitmentsPath(path,stu_id);
		if(essay.equals("final"))
			result = ss.updateEssayPath(path, stu_id);
		return result ? SUCCESS : FAIL;   
	}
	
	
	/**
	 * 退出登陆处理
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout")
	public ModelAndView  LogOut(HttpServletRequest request)
	{
		request.getSession().removeAttribute("user");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("redirect:/showLogin");		
		return mav;
	}
}
